package IO;

import java.io.*;

/**
 *
 * 字符型的字节流
 * @author 15594
 */
public class FileReaderAndWriter {
    public static void main(String[] args) {
        File file = new File("hello.txt");
        System.out.println("文件内容字符长度:"+file.length());
        if (file.isFile()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

//        read(file);
//        try {
//            reads(file);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        write(file);

    }

    private static void write(File file) {
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file);
            fileWriter.write("你好？");
            fileWriter.append("123");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fileWriter!=null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }

    private static void reads(File file) throws IOException {
        FileReader fileReader = new FileReader(file);
        char[] chars = new char[3];

        int len = 0;
        //fileReader.read(chars) 若还有字符则返回读取字符的个数，否则返回-1
        while ((len = fileReader.read(chars)) !=-1){
            for (int i = 0; i <len ; i++) {
                System.out.print(chars[i]);
            }
            System.out.println();
        }
        fileReader.close();
    }

    private static void read(File file) {
        FileReader fileReader =null;
        try {
            fileReader = new FileReader(file);
            //若还有字符则返回读取字符的编码，否则返回-1
            int read = fileReader.read();
            System.out.println("此文件的编码格式："+fileReader.getEncoding());
            if (read!=-1){
                while (read!=-1){
                    read = fileReader.read();
                    System.out.print((char) read);
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileReader!=null){
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }


}
